package com.sk.skplanet.commute.actions;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Vector;

import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.widget.Toast;

import com.sk.skplanet.commute.exceptions.BusAPIException;
import com.sk.skplanet.commute.views.RouteList;
import com.sk.skplanet.commute.vo.Data;
import com.sk.skplanet.commute.vo.Member;

public class LoadingTask extends AsyncTask<Void, String, Boolean> {
	private ProgressDialog dialog;
	private String email;
	private String password;
	private String authkey;
	private String errMsg;
	private Context context;
	private boolean savePassword;

	public LoadingTask(Context context, String authkey) {
		super();
		this.authkey = authkey;
		this.context = context;
	}

	public LoadingTask(Context context, String email, String password, boolean savePassword) {
		super();
		this.email = email;
		this.password = password;
		this.savePassword = savePassword;
		this.context = context;
	}

	private JSONObject getJSON(String URL, List<NameValuePair> params) throws IOException, JSONException,
			BusAPIException {
		String paramString = URLEncodedUtils.format(params, Data.ENCODING);
		String url = URL + "?" + paramString;

		HttpClient httpclient = new DefaultHttpClient();
		HttpGet httpget = new HttpGet(url);

		InputStream is = httpclient.execute(httpget).getEntity().getContent();
		BufferedReader reader = new BufferedReader(new InputStreamReader(is, Data.ENCODING));
		StringBuilder sb = new StringBuilder();
		String line = null;
		while ((line = reader.readLine()) != null)
			sb.append(line + "\n");
		is.close();

		JSONObject result = new JSONObject(sb.toString());

		if (result.getString("success").equals("ERROR")) throw new BusAPIException(result.getString("message"));

		return result;
	}

	@Override
	protected Boolean doInBackground(Void... unused) {
		try {
			Thread.sleep(1000);
			Data.memberData = null;

			Vector<NameValuePair> nameValue = new Vector<NameValuePair>();

			// 1. set arguments.
			if (this.authkey == null || this.authkey.equals("")) {
				nameValue.add(new BasicNameValuePair("email", this.email));
				nameValue.add(new BasicNameValuePair("passwd", this.password));
			} else {
				nameValue.add(new BasicNameValuePair("auth_key", this.authkey));
			}

			// 2. authorizing and getting user identity number.
			JSONObject resultJSON = getJSON(Data.URL_DEFAULT + Data.URL_AUTH, nameValue);
			JSONObject data = resultJSON.getJSONObject("data");
			String userId = data.getString("memberId");
			// Data.AUTH_KEY for use
			Data.AUTH_KEY = data.getString("authKey");

			// 2-2. Update authKey
			if (savePassword) {
				new SQLiteTask().updateAuthKey(data.getString("authKey"));
			}

			// 3. getting user data.
			nameValue = new Vector<NameValuePair>();
			nameValue.add(new BasicNameValuePair("id", userId));
			resultJSON = getJSON(Data.URL_DEFAULT + Data.URL_GET, nameValue);
			try {
				Data.memberData = JsonParsing.parseMemberFromJsonObject(resultJSON);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				if (Data.memberData == null) new Member(Integer.parseInt(userId));

			}

		} catch (BusAPIException e) {
			errMsg = e.getMessage();
			return false;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return true;
	}

	@Override
	protected void onPreExecute() {
		dialog = ProgressDialog.show(context, "", "불러오는 중입니다.", true);
	}

	@Override
	protected void onProgressUpdate(String... item) {
	}

	@Override
	protected void onPostExecute(Boolean success) {
		if (dialog != null) dialog.dismiss();

		if (success) {
			Intent intentRouteList = new Intent(context, RouteList.class);
			context.startActivity(intentRouteList);
			if (context != null) ((Activity) context).finish();

		} else {
			Toast.makeText(context, errMsg, Toast.LENGTH_SHORT).show();
		}
	}
}
